import { Loading } from 'element-ui'
import NProgress from 'nprogress'
import { LoadingConfig } from './types/util.loading'

class LoadingModel {
  loadingInstance: any
  loadingCount = 0
  nprogressCount = 0
  config: LoadingConfig = {}
  loadingConifg: any
  show (config: LoadingConfig): void {
    this.config = config || {}
    this.loadingConifg = config.loading || {}
    if (this.loadingConifg.type && this.loadingConifg.type === 'nprogress') {
      if (this.nprogressCount < 1) {
        NProgress.start()
      }
      this.nprogressCount++
    } else {
      const options: any = {
        fullscreen: true,
        lock: true,
        text: '获取数据中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      }
      Object.assign(options, this.loadingConifg)
      this.loadingInstance = Loading.service(options)
      this.config.loadingInstance = this.loadingInstance
      if (this.loadingCount < 1) {}
      this.loadingCount++
    }
  }

  hide (config: LoadingConfig): void{
    this.config = config || {}
    this.loadingConifg = config.loading || {}
    if (!this.loadingConifg) {
      this.loadingConifg = {}
    }
    if (this.loadingConifg.type && this.loadingConifg.type === 'nprogress') {
      this.nprogressCount--
      if (this.nprogressCount < 1) {
        NProgress.done()
      }
    } else if (config.loadingInstance) {
      this.loadingCount--
      this.config.loadingInstance.close()
      this.config.loadingInstance = null
      if (this.loadingCount < 1) {
        this.loadingInstance = null
      }
    }
  }
}

const loadingInstance = new LoadingModel()
export default loadingInstance
